<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>每日记录</title>

    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5', // 主色调：深紫蓝色
                        secondary: '#10B981', // 辅助色：绿色
                        accent: '#F59E0B', // 强调色：琥珀色
                        neutral: '#F8FAFC', // 背景色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-hover {
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-4px);
                box-shadow: 0 12px 20px rgba(0, 0, 0, 0.08);
            }
            .text-balance {
                text-wrap: balance;
            }
            .carousel-item {
                display: none;
                animation: fadeIn 0.5s ease;
            }
            .carousel-item.active {
                display: block;
            }
            .carousel-indicator {
                width: 10px;
                height: 10px;
                border-radius: 50%;
                background-color: rgba(255, 255, 255, 0.5);
                transition: all 0.3s ease;
            }
            .carousel-indicator.active {
                width: 30px;
                border-radius: 5px;
                background-color: white;
            }
        }
    </style>

    <style>
        /* 基础动画 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .animate-fade-in {
            animation: fadeIn 0.5s ease forwards;
        }

        /* 导航样式 */
        .nav-link {
            position: relative;
            transition: color 0.3s ease;
        }

        .nav-link::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 0;
            height: 2px;
            background-color: #4F46E5;
            transition: width 0.3s ease;
        }

        .nav-link:hover::after,
        .nav-link.active::after {
            width: 100%;
        }

        /* 加载动画 */
        .loader {
            border-top-color: #4F46E5;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 模态框动画 */
        .modal-backdrop {
            opacity: 0;
            transition: opacity 0.3s ease;
            pointer-events: none;
        }

        .modal-backdrop.active {
            opacity: 1;
            pointer-events: auto;
        }

        .modal-content {
            transform: scale(0.95);
            opacity: 0;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        .modal-backdrop.active .modal-content {
            transform: scale(1);
            opacity: 1;
        }

        /* 计划展示样式 */
        .plan-item {
            position: relative;
            padding-left: 1.5rem;
        }

        .plan-item::before {
            content: '✓';
            position: absolute;
            left: 0;
            top: 0;
            color: #10B981;
            font-weight: bold;
        }
    </style>
</head>
<body class="bg-neutral font-sans text-gray-800 min-h-screen">
<!-- 顶部导航 -->
<header class="sticky top-0 z-40 bg-white/95 backdrop-blur-sm shadow-sm">
    <div class="container mx-auto px-4 py-4">
        <div class="flex flex-col md:flex-row justify-between items-center">
            <div class="flex items-center mb-4 md:mb-0">
                <i class="fa fa-book text-primary text-2xl mr-3" aria-hidden="true"></i>
                <h1 class="text-xl md:text-2xl font-bold">每日记录</h1>
            </div>

            <nav class="flex space-x-6">
                <a href="#news" class="nav-link active text-gray-700 hover:text-primary">资讯</a>
                <a href="#plan" class="nav-link text-gray-700 hover:text-primary">计划</a>
                <a href="#diary" class="nav-link text-gray-700 hover:text-primary">日记</a>
            </nav>
        </div>
    </div>
</header>

<main class="container mx-auto px-4 py-8">
    <!-- 日期显示 -->
    <div class="text-center mb-8 animate-fade-in">
        <p id="currentDate" class="text-[clamp(1.5rem,3vw,2.2rem)] font-medium text-gray-800"></p>
        <p id="currentWeekday" class="text-gray-500 mt-1"></p>
    </div>

    <!-- 资讯模块 -->
    <section id="news" class="mb-12 animate-fade-in" style="animation-delay: 0.1s;">
        <h2 class="text-xl md:text-2xl font-bold text-gray-800 mb-6 flex items-center">
            <i class="fa fa-newspaper-o text-accent mr-3" aria-hidden="true"></i>
            今日资讯
        </h2>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- 推荐文章 -->
            <div class="bg-white rounded-xl shadow-sm p-6 md:p-8 card-hover">
                <div class="flex items-center mb-4">
                    <span class="bg-primary/10 text-primary text-sm px-3 py-1 rounded-full">推荐文章</span>
                </div>

                <div id="articleLoader" class="flex justify-center py-10">
                    <div class="loader w-8 h-8 rounded-full border-4 border-gray-200"></div>
                </div>

                <div id="articleContainer" class="hidden">
                    <h3 id="articleTitle" class="text-lg md:text-xl font-semibold mb-3 text-gray-800 hover:text-primary transition-colors cursor-pointer article-detail-trigger"></h3>
                    <p id="articleSummary" class="text-gray-600 mb-4 line-clamp-3 text-balance"></p>
                    <button class="text-primary hover:text-primary/80 flex items-center text-sm font-medium article-detail-trigger">
                        <span>阅读全文</span>
                        <i class="fa fa-angle-right ml-2" aria-hidden="true"></i>
                    </button>
                </div>
            </div>

            <!-- 热点新闻轮播图（取消自动播放） -->
            <div class="bg-white rounded-xl shadow-sm overflow-hidden card-hover">
                <div class="p-4 bg-accent/10">
                    <span class="bg-accent/10 text-accent text-sm px-3 py-1 rounded-full">热点新闻</span>
                </div>

                <div id="newsLoader" class="flex justify-center py-16">
                    <div class="loader w-8 h-8 rounded-full border-4 border-gray-200"></div>
                </div>

                <div id="newsCarousel" class="hidden relative">
                    <!-- 轮播内容容器 -->
                    <div class="carousel-container relative h-[280px]">
                        <!-- 轮播项将通过JS动态生成 -->
                    </div>

                    <!-- 轮播控制按钮 -->
                    <button class="absolute left-2 top-1/2 -translate-y-1/2 w-10 h-10 bg-black/30 hover:bg-black/50 text-white rounded-full flex items-center justify-center transition-colors z-10 carousel-prev">
                        <i class="fa fa-angle-left text-xl" aria-hidden="true"></i>
                    </button>
                    <button class="absolute right-2 top-1/2 -translate-y-1/2 w-10 h-10 bg-black/30 hover:bg-black/50 text-white rounded-full flex items-center justify-center transition-colors z-10 carousel-next">
                        <i class="fa fa-angle-right text-xl" aria-hidden="true"></i>
                    </button>

                    <!-- 轮播指示器 -->
                    <div class="absolute bottom-4 left-1/2 -translate-x-1/2 flex space-x-2 z-10">
                        <!-- 指示器将通过JS动态生成 -->
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 计划模块（移到日记模块前面） -->
    <section id="plan" class="mb-12 animate-fade-in" style="animation-delay: 0.2s;">
        <div class="bg-white rounded-xl shadow-sm p-6 md:p-8 card-hover">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl md:text-2xl font-bold text-gray-800 flex items-center">
                    <i class="fa fa-list-alt text-secondary mr-3" aria-hidden="true"></i>
                    今日计划
                </h2>
                <span id="taskCount" class="bg-secondary/10 text-secondary text-sm px-3 py-1 rounded-full">
            0 项任务
          </span>
            </div>

            <div id="planLoader" class="flex justify-center py-12">
                <div class="loader w-8 h-8 rounded-full border-4 border-gray-200"></div>
            </div>

            <!-- 已有计划时展示容器 -->
            <div id="planDisplayContainer" class="hidden">
                <div class="bg-secondary/5 p-6 rounded-lg border border-secondary/10">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                        <i class="fa fa-check-circle text-secondary mr-2" aria-hidden="true"></i>
                        已制定今日计划
                    </h3>
                    <div id="planDisplayContent" class="space-y-3 text-gray-700">
                        <!-- 计划内容将动态生成 -->
                    </div>
                </div>
            </div>

            <!-- 无计划时输入容器 -->
            <div id="planInputContainer" class="hidden">
                <div class="mb-2 flex justify-between text-sm text-gray-500">
                    <span>提示：每项任务单独一行，使用数字或符号开头更易读</span>
                </div>
                <textarea
                        id="planContent"
                        class="w-full p-4 border border-gray-200 rounded-lg focus:ring-2 focus:ring-secondary/50 focus:border-secondary transition-all resize-none"
                        rows="6"
                        placeholder="1. 早上9:00 参加会议
2. 下午2:00 完成项目文档
..."></textarea>

                <div class="flex justify-end mt-4">
                    <button id="savePlanBtn" class="bg-secondary hover:bg-secondary/90 text-white px-6 py-2.5 rounded-lg transition-all flex items-center">
                        <i class="fa fa-check mr-2" aria-hidden="true"></i>
                        <span>保存计划</span>
                        <span id="savePlanLoader" class="ml-2 hidden">
                <i class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></i>
              </span>
                    </button>
                </div>

                <div id="planSavedNotice" class="mt-4 hidden">
                    <div class="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg flex items-center text-sm">
                        <i class="fa fa-check-circle mr-2" aria-hidden="true"></i>
                        <span>计划已保存！</span>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 日记模块（移到计划模块后面） -->
    <section id="diary" class="mb-12 animate-fade-in" style="animation-delay: 0.3s;">
        <div class="bg-white rounded-xl shadow-sm p-6 md:p-8 card-hover">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl md:text-2xl font-bold text-gray-800 flex items-center">
                    <i class="fa fa-pencil-square-o text-primary mr-3" aria-hidden="true"></i>
                    我的日记
                </h2>
            </div>

            <!-- 写日记区域 -->
            <div class="mb-8">
          <textarea
                  id="diaryContent"
                  class="w-full p-4 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all resize-none"
                  rows="5"
                  placeholder="记录今天的想法和感受..."></textarea>

                <div class="flex justify-end mt-4">
                    <button id="saveDiaryBtn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2.5 rounded-lg transition-all flex items-center">
                        <i class="fa fa-save mr-2" aria-hidden="true"></i>保存日记
                    </button>
                </div>
            </div>

            <!-- 历史日记区域 -->
            <div>
                <h3 class="text-lg font-semibold text-gray-700 mb-4">历史记录</h3>

                <div id="historyDiaryLoader" class="flex justify-center py-8">
                    <div class="loader w-8 h-8 rounded-full border-4 border-gray-200"></div>
                </div>

                <div id="historyDiaryContainer" class="hidden space-y-4">
                    <!-- 历史日记会通过JS动态加载 -->
                </div>

                <div id="noHistoryMessage" class="hidden text-center py-8 text-gray-500">
                    <i class="fa fa-folder-open-o text-4xl mb-3 text-gray-300" aria-hidden="true"></i>
                    <p>暂无历史日记记录</p>
                </div>
            </div>
        </div>
    </section>
</main>

<!-- 页脚 -->
<footer class="bg-white border-t border-gray-200 mt-16">
    <div class="container mx-auto px-4 py-8">
        <div class="text-center text-gray-500 text-sm">
            <p>© <span id="currentYear"></span> 每日记录 | 记录生活的每一刻</p>
        </div>
    </div>
</footer>

<!-- 详情模态框 -->
<div id="detailModal" class="modal-backdrop fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
    <div class="modal-content bg-white rounded-xl max-w-3xl w-full max-h-[85vh] overflow-y-auto m-4">
        <div class="p-6 md:p-8">
            <div class="flex justify-between items-center mb-6">
                <h3 id="modalTitle" class="text-xl md:text-2xl font-bold text-gray-800"></h3>
                <button id="closeModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times text-xl" aria-hidden="true"></i>
                </button>
            </div>

            <div id="modalLoader" class="flex justify-center py-12">
                <div class="loader w-8 h-8 rounded-full border-4 border-gray-200"></div>
            </div>

            <div id="modalContent" class="hidden text-gray-700 leading-relaxed space-y-4">
                <!-- 详情内容将在这里显示 -->
            </div>

            <div id="modalError" class="hidden text-center py-12">
                <i class="fa fa-exclamation-circle text-amber-500 text-4xl mb-4" aria-hidden="true"></i>
                <p class="text-gray-600">获取内容详情失败，请稍后重试</p>
            </div>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div id="toast" class="fixed bottom-6 right-6 bg-gray-800 text-white px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50">
    <i id="toastIcon" class="fa mr-2" aria-hidden="true"></i>
    <span id="toastMessage"></span>
</div>

<script>
    // 存储当前详情类型（文章/新闻）
    let currentDetailType = '';
    let currentNewsIndex = 0;
    let newsData = [];

    // 初始化页面
    document.addEventListener('DOMContentLoaded', () => {
        // 设置当前日期
        updateDateInfo();

        // 优先加载顶部的资讯内容
        fetchArticle();
        fetchNews();

        // 加载其他模块数据（先加载计划，再加载日记）
        fetchPlan();
        fetchHistoryDiaries();

        // 绑定导航事件
        bindNavEvents();

        // 绑定按钮事件
        bindButtonEvents();

        // 绑定详情查看事件
        bindDetailEvents();

        // 绑定模态框事件
        bindModalEvents();

        // 绑定计划文本域事件
        bindPlanEvents();
    });

    // 更新日期信息
    function updateDateInfo() {
        const now = new Date();
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        const weekdayOptions = { weekday: 'long' };

        document.getElementById('currentDate').textContent = now.toLocaleDateString('zh-CN', options);
        document.getElementById('currentWeekday').textContent = now.toLocaleDateString('zh-CN', weekdayOptions);
        document.getElementById('currentYear').textContent = now.getFullYear();
    }

    // 导航事件绑定
    function bindNavEvents() {
        const navLinks = document.querySelectorAll('.nav-link');

        navLinks.forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();

                // 更新活跃状态
                navLinks.forEach(item => item.classList.remove('active'));
                link.classList.add('active');

                // 平滑滚动到对应区域
                const targetId = link.getAttribute('href').substring(1);
                const targetElement = document.getElementById(targetId);

                window.scrollTo({
                    top: targetElement.offsetTop - 80,
                    behavior: 'smooth'
                });
            });
        });
    }

    // 按钮事件绑定
    function bindButtonEvents() {
        // 保存日记按钮
        document.getElementById('saveDiaryBtn').addEventListener('click', saveDiary);

        // 保存计划按钮
        document.getElementById('savePlanBtn').addEventListener('click', savePlan);
    }

    // 计划文本域事件绑定
    function bindPlanEvents() {
        const planContent = document.getElementById('planContent');
        const taskCount = document.getElementById('taskCount');

        // 实时更新任务数量（仅无计划时生效）
        if (planContent) {
            planContent.addEventListener('input', () => {
                const content = planContent.value.trim();
                const count = content ? content.split('\n').filter(line => line.trim()).length : 0;
                taskCount.textContent = `${count} 项任务`;

                // 隐藏保存提示
                document.getElementById('planSavedNotice').classList.add('hidden');
            });
        }
    }

    // 详情查看事件绑定
    function bindDetailEvents() {
        // 文章详情触发
        document.addEventListener('click', (e) => {
            if (e.target.closest('.article-detail-trigger')) {
                currentDetailType = 'article';
                openDetailModal('推荐文章', fetchArticleDetails);
            }
        });

        // 新闻详情触发
        document.addEventListener('click', (e) => {
            if (e.target.closest('.news-detail-trigger')) {
                currentDetailType = 'news';
                // 获取当前点击的新闻索引
                const index = parseInt(e.target.closest('.news-detail-trigger').dataset.index);
                currentNewsIndex = index;
                openDetailModal('热点新闻', fetchNewsDetails);
            }
        });
    }

    // 轮播图事件绑定（仅保留手动切换）
    function bindCarouselEvents() {
        const prevBtn = document.querySelector('.carousel-prev');
        const nextBtn = document.querySelector('.carousel-next');
        const indicators = document.querySelectorAll('.carousel-indicator');

        // 上一张
        prevBtn.addEventListener('click', () => {
            currentNewsIndex = (currentNewsIndex - 1 + newsData.length) % newsData.length;
            updateCarousel();
        });

        // 下一张
        nextBtn.addEventListener('click', () => {
            currentNewsIndex = (currentNewsIndex + 1) % newsData.length;
            updateCarousel();
        });

        // 点击指示器
        indicators.forEach((indicator, index) => {
            indicator.addEventListener('click', () => {
                currentNewsIndex = index;
                updateCarousel();
            });
        });
    }

    // 更新轮播图显示
    function updateCarousel() {
        const items = document.querySelectorAll('.carousel-item');
        const indicators = document.querySelectorAll('.carousel-indicator');

        // 更新轮播项
        items.forEach((item, index) => {
            if (index === currentNewsIndex) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });

        // 更新指示器
        indicators.forEach((indicator, index) => {
            if (index === currentNewsIndex) {
                indicator.classList.add('active');
            } else {
                indicator.classList.remove('active');
            }
        });
    }

    // 模态框事件绑定
    function bindModalEvents() {
        // 关闭按钮
        document.getElementById('closeModal').addEventListener('click', closeDetailModal);

        // 点击外部关闭
        document.getElementById('detailModal').addEventListener('click', (e) => {
            if (e.target === document.getElementById('detailModal')) {
                closeDetailModal();
            }
        });

        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && document.getElementById('detailModal').classList.contains('active')) {
                closeDetailModal();
            }
        });
    }

    // 打开详情模态框
    function openDetailModal(title, fetchFn) {
        const modal = document.getElementById('detailModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalLoader = document.getElementById('modalLoader');
        const modalContent = document.getElementById('modalContent');
        const modalError = document.getElementById('modalError');

        // 设置标题
        modalTitle.textContent = title;

        // 显示加载状态
        modalLoader.classList.remove('hidden');
        modalContent.classList.add('hidden');
        modalError.classList.add('hidden');

        // 显示模态框
        modal.classList.add('active');

        // 禁止背景滚动
        document.body.style.overflow = 'hidden';

        // 调用获取详情的函数
        fetchFn();
    }

    // 关闭详情模态框
    function closeDetailModal() {
        const modal = document.getElementById('detailModal');

        // 隐藏模态框
        modal.classList.remove('active');

        // 恢复背景滚动
        document.body.style.overflow = '';
    }

    // 获取文章详情
    async function fetchArticleDetails() {
        const modalLoader = document.getElementById('modalLoader');
        const modalContent = document.getElementById('modalContent');
        const modalError = document.getElementById('modalError');

        try {
            // 调用文章详情接口
            const response = await fetch('http://localhost:6512/article/details');

            if (!response.ok) {
                throw new Error('获取文章详情失败');
            }

            const details = await response.text();

            // 显示详情内容，处理换行
            modalLoader.classList.add('hidden');
            modalContent.classList.remove('hidden');
            modalContent.innerHTML = details.split('\n').map(paragraph =>
                paragraph ? `<p>${paragraph}</p>` : '<br>'
            ).join('');
        } catch (error) {
            console.error('获取文章详情失败:', error);
            modalLoader.classList.add('hidden');
            modalError.classList.remove('hidden');
        }
    }

    // 获取新闻详情
    async function fetchNewsDetails() {
        const modalLoader = document.getElementById('modalLoader');
        const modalContent = document.getElementById('modalContent');
        const modalError = document.getElementById('modalError');

        try {
            // 调用新闻详情接口
            const response = await fetch('http://localhost:6512/day/newsDetails');

            if (!response.ok) {
                throw new Error('获取新闻详情失败');
            }

            const details = await response.text();

            // 显示详情内容，处理换行
            modalLoader.classList.add('hidden');
            modalContent.classList.remove('hidden');
            modalContent.innerHTML = details.split('\n').map(paragraph =>
                paragraph ? `<p>${paragraph}</p>` : '<br>'
            ).join('');
        } catch (error) {
            console.error('获取新闻详情失败:', error);
            modalLoader.classList.add('hidden');
            modalError.classList.remove('hidden');
        }
    }

    // 显示通知提示
    function showToast(message, isSuccess = true) {
        const toast = document.getElementById('toast');
        const toastIcon = document.getElementById('toastIcon');
        const toastMessage = document.getElementById('toastMessage');

        toastMessage.textContent = message;
        toastIcon.className = isSuccess ? 'fa fa-check-circle mr-2' : 'fa fa-exclamation-circle mr-2';

        // 显示通知
        toast.classList.remove('translate-y-20', 'opacity-0');
        toast.classList.add('translate-y-0', 'opacity-100');

        // 3秒后隐藏
        setTimeout(() => {
            toast.classList.remove('translate-y-0', 'opacity-100');
            toast.classList.add('translate-y-20', 'opacity-0');
        }, 3000);
    }

    // 保存日记
    async function saveDiary() {
        const content = document.getElementById('diaryContent').value.trim();

        if (!content) {
            showToast('日记内容不能为空', false);
            return;
        }

        try {
            // 调用写日记接口
            const response = await fetch('http://localhost:6512/write/one', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ content: content })
            });

            if (response.ok) {
                showToast('日记保存成功');
                document.getElementById('diaryContent').value = '';
                // 重新加载历史日记
                fetchHistoryDiaries();
            } else {
                throw new Error('保存失败');
            }
        } catch (error) {
            console.error('保存日记失败:', error);
            showToast('保存日记失败，请重试', false);
        }
    }

    // 获取历史日记
    async function fetchHistoryDiaries() {
        const loader = document.getElementById('historyDiaryLoader');
        const container = document.getElementById('historyDiaryContainer');
        const noHistoryMsg = document.getElementById('noHistoryMessage');

        // 显示加载状态
        loader.classList.remove('hidden');
        container.classList.add('hidden');
        noHistoryMsg.classList.add('hidden');

        try {
            // 调用获取历史日记接口
            const response = await fetch('http://localhost:6512/get/somedays');

            if (!response.ok) {
                throw new Error('获取历史日记失败');
            }

            const diaries = await response.json();

            // 隐藏加载状态
            loader.classList.add('hidden');

            if (diaries && diaries.length > 0) {
                // 显示日记列表
                container.classList.remove('hidden');
                container.innerHTML = '';

                diaries.forEach(diary => {
                    // 解析日期、天气和内容
                    const [datePart, ...contentParts] = diary.split(' ');
                    const weather = contentParts[0] || '';
                    const content = contentParts.slice(1).join(' ').replace('：', '');

                    const diaryCard = document.createElement('div');
                    diaryCard.className = 'p-4 border border-gray-100 rounded-lg hover:border-primary/30 transition-colors';
                    diaryCard.innerHTML = `
              <div class="flex justify-between items-start mb-2">
                <span class="text-sm font-medium text-gray-600">${datePart}</span>
                <span class="text-xs px-2 py-1 bg-gray-100 text-gray-500 rounded-full">
                  <i class="fa fa-${getWeatherIcon(weather)} mr-1" aria-hidden="true"></i>${weather}
                </span>
              </div>
              <p class="text-gray-700 text-sm line-clamp-2">${content}</p>
            `;
                    container.appendChild(diaryCard);
                });
            } else {
                // 显示无记录提示
                noHistoryMsg.classList.remove('hidden');
            }
        } catch (error) {
            console.error('获取历史日记失败:', error);
            loader.classList.add('hidden');
            noHistoryMsg.classList.remove('hidden');
            noHistoryMsg.innerHTML = `
          <i class="fa fa-exclamation-o text-4xl mb-3 text-gray-300" aria-hidden="true"></i>
          <p>获取历史记录失败</p>
        `;
        }
    }

    // 获取天气对应的图标
    function getWeatherIcon(weather) {
        switch(weather) {
            case '晴': return 'sun-o';
            case '多云': return 'cloud';
            case '小雨': return 'tint';
            case '阴': return 'cloud';
            case '雷阵雨': return 'bolt';
            default: return 'question-circle';
        }
    }

    // 获取今日计划（优化逻辑：已有计划则展示，无则显示输入框）
    async function fetchPlan() {
        const loader = document.getElementById('planLoader');
        const displayContainer = document.getElementById('planDisplayContainer');
        const inputContainer = document.getElementById('planInputContainer');
        const displayContent = document.getElementById('planDisplayContent');
        const taskCount = document.getElementById('taskCount');

        try {
            // 调用获取计划接口
            const response = await fetch('http://localhost:6512/day/plan');

            if (!response.ok) {
                throw new Error('获取计划失败');
            }

            const plan = await response.text();
            const planItems = plan ? plan.split('\n').filter(line => line.trim()) : [];

            // 更新任务数量
            taskCount.textContent = `${planItems.length} 项任务`;

            // 隐藏加载状态
            loader.classList.add('hidden');

            // 判断是否已有计划
            if (planItems.length > 0) {
                // 已有计划：显示展示容器，隐藏输入容器
                displayContainer.classList.remove('hidden');
                inputContainer.classList.add('hidden');

                // 渲染计划内容
                displayContent.innerHTML = '';
                planItems.forEach((item, index) => {
                    const planItem = document.createElement('div');
                    planItem.className = 'plan-item py-1 border-b border-gray-100 last:border-0';
                    planItem.textContent = item.trim();
                    displayContent.appendChild(planItem);
                });
            } else {
                // 无计划：显示输入容器，隐藏展示容器
                inputContainer.classList.remove('hidden');
                displayContainer.classList.add('hidden');
            }
        } catch (error) {
            console.error('获取计划失败:', error);
            loader.classList.add('hidden');
            // 错误时显示输入容器
            inputContainer.classList.remove('hidden');
            displayContainer.classList.add('hidden');
            document.getElementById('planContent').value = '获取计划失败，请手动输入...';
            taskCount.textContent = '0 项任务';
        }
    }

    // 保存今日计划
    async function savePlan() {
        const content = document.getElementById('planContent').value.trim();
        const saveBtn = document.getElementById('savePlanBtn');
        const saveLoader = document.getElementById('savePlanLoader');
        const savedNotice = document.getElementById('planSavedNotice');

        // 显示加载状态
        saveBtn.disabled = true;
        saveLoader.classList.remove('hidden');
        savedNotice.classList.add('hidden');

        try {
            // 调用保存计划接口
            const response = await fetch('http://localhost:6512/update/plan', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `request=${encodeURIComponent(content)}`
            });

            if (response.ok) {
                const result = await response.text();
                savedNotice.classList.remove('hidden');
                savedNotice.querySelector('span').textContent = result;

                // 保存成功后刷新计划展示
                setTimeout(() => {
                    fetchPlan();
                }, 1500);
            } else {
                throw new Error('保存计划失败');
            }
        } catch (error) {
            console.error('保存计划失败:', error);
            showToast('保存计划失败，请重试', false);
        } finally {
            // 恢复状态
            saveBtn.disabled = false;
            saveLoader.classList.add('hidden');
        }
    }

    // 获取推荐文章
    async function fetchArticle() {
        const loader = document.getElementById('articleLoader');
        const container = document.getElementById('articleContainer');
        const title = document.getElementById('articleTitle');
        const summary = document.getElementById('articleSummary');

        try {
            // 调用获取文章接口
            const response = await fetch('http://localhost:6512/day/article');

            if (!response.ok) {
                throw new Error('获取文章失败');
            }

            const article = await response.text();

            // 显示文章内容（这里简单处理为标题和摘要）
            loader.classList.add('hidden');
            container.classList.remove('hidden');

            // 如果有内容，简单分割为标题和摘要
            if (article) {
                const parts = article.split('\n');
                title.textContent = parts[0] || '今日推荐文章';
                summary.textContent = parts.slice(1).join('\n') || '点击查看详情...';
            } else {
                title.textContent = '今日推荐文章';
                summary.textContent = '暂无推荐文章，敬请期待...';
            }
        } catch (error) {
            console.error('获取文章失败:', error);
            loader.classList.add('hidden');
            container.classList.remove('hidden');
            title.textContent = '获取文章失败';
            summary.textContent = '无法加载推荐文章，请稍后重试...';
        }
    }

    // 获取推荐新闻（轮播图，取消自动播放）
    async function fetchNews() {
        const loader = document.getElementById('newsLoader');
        const carousel = document.getElementById('newsCarousel');
        const carouselContainer = carousel.querySelector('.carousel-container');
        const indicatorsContainer = carousel.querySelector('.absolute.bottom-4');

        try {
            // 调用获取新闻接口
            const response = await fetch('http://localhost:6512/day/news');

            if (!response) {
                throw new Error('获取新闻失败');
            }

            newsData = await response.json();

            // 隐藏加载状态，显示轮播图
            loader.classList.add('hidden');
            carousel.classList.remove('hidden');

            // 清空容器
            carouselContainer.innerHTML = '';
            indicatorsContainer.innerHTML = '';

            if (newsData && newsData.length > 0) {
                // 生成轮播项和指示器
                newsData.forEach((news, index) => {
                    // 分割标题和摘要
                    const parts = news.split('\n');
                    const newsTitle = parts[0] || '热点新闻';
                    const newsSummary = parts.slice(1).join('\n') || '点击查看详情...';

                    // 创建轮播项
                    const carouselItem = document.createElement('div');
                    carouselItem.className = `carousel-item ${index === 0 ? 'active' : ''} absolute inset-0 p-6 flex flex-col`;
                    carouselItem.innerHTML = `
              <h3 class="text-lg md:text-xl font-semibold mb-3 text-white text-shadow-md news-detail-trigger" data-index="${index}">${newsTitle}</h3>
              <p class="text-gray-100 mb-4 flex-grow news-detail-trigger" data-index="${index}">${newsSummary}</p>
              <button class="text-white hover:text-gray-200 flex items-center text-sm font-medium self-start news-detail-trigger" data-index="${index}">
                <span>查看详情</span>
                <i class="fa fa-angle-right ml-2" aria-hidden="true"></i>
              </button>
            `;
                    // 设置背景渐变，提高文字可读性
                    carouselItem.style.background = `linear-gradient(rgba(0,0,0,0.2), rgba(0,0,0,0.6)), url('https://picsum.photos/seed/news${index}/800/400') center/cover no-repeat`;
                    carouselContainer.appendChild(carouselItem);

                    // 创建指示器
                    const indicator = document.createElement('button');
                    indicator.className = `carousel-indicator ${index === 0 ? 'active' : ''}`;
                    indicator.setAttribute('aria-label', `查看第 ${index + 1} 条新闻`);
                    indicatorsContainer.appendChild(indicator);
                });

                // 绑定轮播手动切换事件
                bindCarouselEvents();
            } else {
                // 没有新闻数据
                carouselContainer.innerHTML = `
            <div class="flex flex-col items-center justify-center h-full text-gray-500">
              <i class="fa fa-newspaper-o text-4xl mb-3" aria-hidden="true"></i>
              <p>暂无热点新闻，敬请期待</p>
            </div>
          `;
            }
        } catch (error) {
            console.error('获取新闻失败:', error);
            loader.classList.add('hidden');
            carousel.classList.remove('hidden');
            carouselContainer.innerHTML = `
          <div class="flex flex-col items-center justify-center h-full text-gray-500">
            <i class="fa fa-exclamation-circle text-4xl mb-3" aria-hidden="true"></i>
            <p>获取新闻失败，请稍后重试</p>
          </div>
        `;
        }
    }
</script>
</body>
</html>